import { FOOD_RADIUS } from './constant'

/**
 * 1.创建食物属性
 * @param {CanvasRenderingContext2D} ctx canvas2d渲染上下文
 * @returns {StatePosition} 食物属性
 */
export function createFoodPosition(
  ctx: CanvasRenderingContext2D
): StatePosition {
  const { width, height } = ctx.canvas
  return {
    x: FOOD_RADIUS + 10 + Math.random() * (width - (FOOD_RADIUS + 10) * 2),
    y: FOOD_RADIUS + 10 + Math.random() * (height - (FOOD_RADIUS + 10) * 2),
    r: FOOD_RADIUS,
    color: `rgb(${Math.floor(Math.random() * 255)}, ${Math.floor(
      Math.random() * 255
    )}, ${Math.floor(Math.random() * 255)})`
  }
}

/**
 * 2.根据数据绘制canvas
 * @param {CanvasRenderingContext2D} ctx canvas2d渲染上下文
 * @param {State} state 数据
 * @returns 无
 */
export function draw(ctx: CanvasRenderingContext2D, state: State): void {
  const {
    user: { x: ux, y: uy, r: ur, color: uc },
    food: { x: fx, y: fy, r: fr, color: fc }
  } = state
  const { width, height } = ctx.canvas
  ctx.clearRect(0, 0, width, height)

  // 1.绘制角色
  ctx.save()
  ctx.translate(ux, uy)
  ctx.fillStyle = uc
  ctx.beginPath()
  ctx.arc(0, 0, ur, 0, 2 * Math.PI, false)
  ctx.closePath()
  ctx.fill()
  ctx.restore()

  // 2.绘制食物
  ctx.save()
  ctx.translate(fx, fy)
  ctx.fillStyle = fc
  ctx.beginPath()
  ctx.arc(0, 0, fr, 0, 2 * Math.PI, false)
  ctx.closePath()
  ctx.fill()
  ctx.restore()
}

/**
 * 3.边缘碰撞检测
 * @param {CanvasRenderingContext2D} ctx canvas2d渲染上下文
 * @param {State} state 数据
 * @returns 是否碰撞
 */
export function detectionEdge(
  ctx: CanvasRenderingContext2D,
  state: State
): boolean {
  const { width, height } = ctx.canvas
  const {
    user: { x, y, r }
  } = state

  let result = true

  if (x - r <= 0 || x + r >= width || y - r <= 0 || y + r >= height) {
    result = false
  }

  return result
}

/**
 * 4.食物碰撞检测
 * @param {CanvasRenderingContext2D} ctx canvas2d渲染上下文
 * @param {State} state 数据
 * @returns 是否碰撞
 */
export function detectionFood(state: State): boolean {
  const { user, food } = state
  const minDistance = user.r + food.r

  let result = false

  // 计算圆心之间距离
  const distance = Math.sqrt(
    Math.abs(user.x - food.x) ** 2 + Math.abs(user.y - food.y) ** 2
  )
  if (distance <= minDistance) {
    result = true
  }

  return result
}
